import Vue from 'vue'
import Router from 'vue-router'
import { userInfo } from '../utils/config'
Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('../pages/home/index.vue'),
      meta: {
        title: '首页'
      }
    },
    {
      path: '/signUp',
      name: 'SignUp',
      component: () => import('../pages/signUp/index.vue'),
      meta: {
        title: '注册'
      }
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../pages/login/index.vue'),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/order',
      name: 'Order',
      component: () => import('../pages/order/index.vue'),
      meta: {
        title: '订单'
      }
    },
    {
      path: '/cart',
      name: 'Cart',
      component: () => import('../pages/cart/index.vue'),
      meta: {
        title: '购物车'
      }
    },
    {
      path: '/cashier',
      name: 'Cashier',
      component: () => import('../pages/cashier/index.vue'),
      meta: {
        title: '付款'
      }
    },
    {
      path: '/my',
      name: 'My',
      component: () => import('../pages/my/index.vue'),
      meta: {
        title: '个人中心',
        requiresAuth: false
      }
    },
    {
      path: '/search',
      name: 'Search',
      component: () => import('../pages/search/index.vue'),
      meta: {
        title: '搜索',
        requiresAuth: false
      }
    },
    {
      path: '/detail',
      name: 'Detail',
      component: () => import('../pages/detail/index.vue'),
      meta: {
        title: '详情',
        requiresAuth: false
      }
    },
    {
      path: '/user',
      name: 'User',
      component: () => import('../pages/user/index.vue'),
      meta: {
        title: '个人资料',
        requiresAuth: false
      }
    },
    {
      path: '/updateUser',
      name: 'UpdateUser',
      component: () => import('../pages/updateUser/index.vue'),
      meta: {
        title: '修改个人资料',
        requiresAuth: false
      }
    },
    {
      path: '/more',
      name: 'More',
      component: () => import('../pages/more/index.vue'),
      meta: {
        title: '更多',
        requiresAuth: false
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    let token = this.$Cookies.get()
    let usid = localStorage.getItem(userInfo) ? JSON.parse(localStorage.getItem(userInfo)).userId : ''
    if (token && usid) {
      next()
    } else {
      router.replace({
        path: '/signin',
        query: {
          redirect: router.currentRoute.fullPath
        } // 登录成功后跳入浏览的当前页面
      })
      // next('/signin')
    }
  } else {
    next()
  }
})
export default router
